package main

import (
	"bufio"
	"fmt"
	"golang.org/x/net/html/charset"
	"golang.org/x/text/transform"
	"io/ioutil"
	"net/http"
)


var (
	i int = 3
	s string = "b"
)
func responseBody(r *http.Response) {
	content, err := ioutil.ReadAll(r.Body)
	if err != nil {
		panic(err)
	}
	fmt.Printf("%s", content)
}

func status(r *http.Response) {
	fmt.Println(r.Status)     //状态信息
	fmt.Println(r.StatusCode) //状态码
}

func header(r *http.Response) {
	fmt.Println(r.Header.Get("Content-type"))
}

func encoding(r *http.Response) {
	// 1. content-type 中会提供编码信息，比如 content-type="test/html;charset=utf-8"
	// 2. html head meta 中获取编码信息
	//    <meta http-equiv=Content-Type content="text/html;charset=utf-8"
	// 3. 如果以上两者都没有可以通过网页的头部猜测编码信息
	bufReader := bufio.NewReader(r.Body)
	bytes, _ := bufReader.Peek(1024)
	e, _, _ := charset.DetermineEncoding(bytes, r.Header.Get("content-type"))
	fmt.Println(e)

	bodyReader := transform.NewReader(bufReader, e.NewDecoder())
	content, _ := ioutil.ReadAll(bodyReader)
	fmt.Printf("%s", content)
}

func main() {
	r, err := http.Get("https://baidu.com")
	if err != nil {
		panic(err)
	}
	defer func() { _ = r.Body.Close() }()

	//status(r)
	//header(r)
	encoding(r)
}
